<template>
  <div class="dataEdit">
    <div>
      <div>
        <vxe-button status="success" content="保存" size="mini" @click="Save()" v-if="![1,2,8,9].includes(formData.StatusCode)"></vxe-button>
        <vxe-button status="success" v-if="formData.StatusCode!==8&&Template.allowBestFitColumns===1" content="审核" size="mini" @click="handleCheck(8)"></vxe-button>
        <vxe-button status="success" v-if="formData.StatusCode===8&&Template.allowBestFitColumns===1" content="反审" size="mini" @click="handleCheck(0)"></vxe-button>
        <vxe-button status="success" size="mini" content="审批流程" v-if="Template.allowBestFitColumns===2" @click="processbutton()"></vxe-button>
        <vxe-button size="mini" status="primary" style="margin: 0 10px !important;" transfer placement="bottom" v-for="(items,key) in ManualActRules"
                    v-if="![1,2,9].includes(formData.StatusCode)">
          <template #default>{{ key }}</template>
          <template #dropdowns>
            <vxe-button type="text" v-for="(item,index) in items" :content="item.ruleName"
                        @click="runActRules(item)"></vxe-button>
          </template>
        </vxe-button>
      </div>
      <div style="font-size: 1.55em; text-align: center; margin-top: 10px;"> {{ Title }}</div>
    </div>
    
    <vxe-form :data="formData" :ref="el=>{refForm=el}" :rules="Rules[MT.tableName]" size="small" title-width="100">
      
      <vxe-form-item :visible="false" field="RecordID"></vxe-form-item>
      <vxe-form-item v-for="item in  Fields[MT.tableName]" :key="item.fieldID" :span="isequipment?8:24"
                     :title="item.fieldDispName" :visible="item.hidden===0" :field="item.fieldName" :title-width="item.allowFixedWidth>0?item.allowFixedWidth:100"
                     :item-render="{events:{change:ValueChange}}">
        <template #default="{ data }">
          <div v-if="item.dataTypeID===1">
            <vxe-input v-model="data[item.fieldName]" v-show="item.componentID===0" :readonly="item.editable===0||formData.statusCode!==0"
                       @blur="ValueChange(data,Fields[MT.tableName],item.fieldName)"></vxe-input>

            <el-input size="default" v-show="item.componentID>0"
                      @change="ValueChange(data,Fields[MT.tableName],item.fieldName)" placeholder="请点击选择..."
                      v-if="item.componentID>0 && [3,6].includes(item.componentType)" type="text"
                      :value="getextend(data,item)">
              <template #append>
                <el-button @click="showSource({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName})"
                           :disabled="item.editable===0||formData.statusCode!==0"
                           size="default" :icon="Plus"/>
              </template>
            </el-input>
            <vxe-select v-if="item.componentID>0 && item.componentType===1" :disabled="item.editable===0||formData.statusCode!==0"
                        v-model="data[item.fieldName]" placeholder="下拉框" clearable
                        @change="ValueChange(data,Fields[MT.tableName],item.fieldName)" transfer>
              <vxe-option v-for="(it,index) in Combo[item.fieldName]" :value="it.value" :label="it.label"
                          :key="index"></vxe-option>
            </vxe-select>
            <vxe-input v-if="item.componentID>0 && item.componentType===5" v-model="data[item.fieldName]"
                       :readonly="item.editable===0||formData.statusCode!==0" placeholder="自动取得编号"
                       @suffix-click="getAutoCode( Fields[MT.tableName],formData,item.fieldName)">
              <template #suffix><i class="el-icon-refresh-right"></i></template>
            </vxe-input>
          </div>
          <vxe-input v-if="item.dataTypeID===2" v-model="data[item.fieldName]" :readonly="item.editable===0||formData.statusCode!==0"
                     placeholder="请输入..." type="integer"
                     @blur="ValueChange(data,Fields[MT.tableName],item.fieldName)"></vxe-input>
          <vxe-input v-if="item.dataTypeID===3" v-model="data[item.fieldName]" :readonly="item.editable===0||formData.statusCode!==0"
                     placeholder="请输入..." clearable type="float" :digits="item.fieldPrecision"
                     @blur="ValueChange(data,Fields[MT.tableName],item.fieldName)"></vxe-input>
          <vxe-input v-if="item.dataTypeID===4" v-model="data[item.fieldName]" :readonly="item.editable===0||formData.statusCode!==0" transfer
                     placeholder="请输入..." clearable type="date"
                     @blur="ValueChange(data,Fields[MT.tableName],item.fieldName)"></vxe-input>
          <div v-if="[5,10].includes(item.dataTypeID)">
            <vxe-input v-model="data[item.fieldName]" v-show="false"></vxe-input>
            <!-- <vxe-input  :value="getextend(data,item)" placeholder="请选择图片" readonly   class="my-search" @suffix-click="showFiles({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName,multiple:false,fileType:'images'})" @blur="ValueChange(data,Fields[MT.tableName],item.fieldName)">
              <template #suffix >
                <el-icon><Plus /></el-icon>
              </template>
            </vxe-input> -->
            <el-input size="default" @change="ValueChange(data,Fields[MT.tableName],item.fieldName)" placeholder="请选择图片"
                      type="text" :value="getextend(data,item)">
              <template #append>
                <el-button :disabled="item.editable===0||formData.statusCode!==0"
                    @click="showFiles({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName,multiple:false,fileType:'images'})"
                    size="default" :icon="Plus"/>
              </template>
            </el-input>
          </div>
          <div v-if="item.dataTypeID===6">
            <vxe-input v-model="data[item.fieldName]" v-show="false"></vxe-input>
            <!-- <vxe-input  :value="getextend(data,item)" placeholder="请选择文件" readonly   class="my-search" @suffix-click="showFiles({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName,multiple:true,fileType:'files'})" @blur="ValueChange(data,Fields[MT.tableName],item.fieldName)">
              <template #suffix >
                <el-icon><Plus /></el-icon>
              </template>
            </vxe-input> -->
            <el-input size="default" @change="ValueChange(data,Fields[MT.tableName],item.fieldName)" placeholder="请选择文件"
                      type="text" :value="getextend(data,item)">
              <template #append>
                <el-button :disabled="item.editable===0||formData.statusCode!==0"
                    @click="showFiles({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName,multiple:true,fileType:'files'})"
                    size="default" :icon="Plus"/>
              </template>
            </el-input>
          </div>
          <vxe-input v-if="item.dataTypeID===7" v-model="data[item.fieldName]" :readonly="item.editable===0||formData.statusCode!==0"
                     placeholder="请输入..." clearable
                     @blur="ValueChange(data,Fields[MT.tableName],item.fieldName)"></vxe-input>
        </template>
      </vxe-form-item>
      <!-- <vxe-form-item field="Extend" :visible="false"></vxe-form-item> -->
    </vxe-form>
    <div>
      <el-tabs type="border-card" style="height: 100%;" v-if=" DT.length>0">
        <el-tab-pane :label="tb.tableTitle" v-for="(tb ,name) in DT" >
          <vxe-form v-for="(items,index) in DetailsData[tb.tableName]"  :ref="el=>itemRefs[tb.tableName+'_'+index]=el"
                    :rules="Rules[tb.tableName]" :key="index" size="mini" :data="items" title-align="right"
                    title-width="100" prevent-submit title-colon custom-layout>
            <div style="border: 1px dashed green;padding: 10px;margin-bottom: 5px">
              <div class="index">{{ index + 1 }}</div>
              <vxe-form-item v-for="item in  Fields[tb.tableName]" :key="item.fieldID" span="24"
                             :title="item.fieldDispName" v-show="item.hidden===0" :field="item.fieldName"
                             :item-render="{defaultValue:item.default}">
                <template #default="{ data }">
                  <div v-if="item.dataTypeID===1">
                    <vxe-input v-model="data[item.fieldName]" v-show="item.componentID===0" :readonly="item.editable===0||formData.statusCode!==0"
                               @blur="ValueChange(data,Fields[tb.tableName],item.fieldName)"></vxe-input>
                    <el-input  v-if="item.componentID>0 && [3,6].includes(item.componentType)" type="text" readonly v-show="item.componentID>0"
                              @change="ValueChange(data,Fields[tb.tableName],item.fieldName)" placeholder="请点击选择..."

                              :value="getextend(data,item)">
                      <template #append>
                        <el-button @click="showSource({item:item ,value:data[item.fieldName],target:items,ref:tb.tableName})"
                                   size="default" :icon="Plus"/>
                      </template>
                    </el-input>

                    <vxe-select v-if="item.componentID>0 && item.componentType===1" :readonly="item.editable===0||formData.statusCode!==0"
                                v-model="data[item.fieldName]" placeholder="下拉框"
                                @blur="ValueChange(row,Fields[tb.tableName],item.fieldName)" clearable transfer>
                      <vxe-option v-for="(it,index) in Combo[item.fieldName]" :value="it.value" :label="it.label"
                                  :key="index"></vxe-option>
                    </vxe-select>

                    <vxe-input v-if="item.componentID>0 && item.componentType===5" v-model="data[item.fieldName]"
                               :readonly="item.editable===0||formData.statusCode!==0" placeholder="自动取得编号"
                               @suffix-click="getAutoCode( Fields[tb.tableName],data,item.fieldName)">
                      <template #suffix><el-icon><Plus /></el-icon></template>
                    </vxe-input>
                  </div>

                  <vxe-input v-if="item.dataTypeID===2" v-model="data[item.fieldName]" placeholder="请输入..."
                             :readonly="item.editable===0||formData.statusCode!==0" type="integer"
                             @blur="ValueChange(data,Fields[tb.tableName],item.fieldName)"></vxe-input>
                  <vxe-input v-if="item.dataTypeID===3" v-model="data[item.fieldName]" placeholder="请输入..."
                             :readonly="item.editable===0||formData.statusCode!==0" clearable type="float" :digits="item.fieldPrecision"
                             @blur="ValueChange(data,Fields[tb.tableName],item.fieldName)"></vxe-input>
                  <vxe-input v-if="item.dataTypeID===4" v-model="data[item.fieldName]" placeholder="请输入..."
                             :readonly="item.editable===0||formData.statusCode!==0" transfer clearable type="date"
                             @blur="ValueChange(data,Fields[tb.tableName],item.fieldName)"></vxe-input>
                  <div v-if="[5,10].includes(item.dataTypeID)">
                    <vxe-input v-model="data[item.fieldName]" v-show="false"></vxe-input>
                    <vxe-input :value="getextend(data,item)" placeholder="请选择图片" readonly class="my-search"
                               @suffix-click="showFiles({item:item ,value:data[item.fieldName],target:data,ref:item.tableName,multiple:false,fileType:'images'})"
                               @blur="ValueChange(data,Fields[tb.tableName],item.fieldName)">
                      <template #suffix>
                        <i class="el-icon-plus"></i>
                      </template>
                    </vxe-input>
                  </div>
                  <div v-if="item.dataTypeID===6">
                    <vxe-input v-model="data[item.fieldName]" v-show="false"></vxe-input>
                    <vxe-input :value="getextend(data,item)" placeholder="请选择文件" readonly class="my-search"
                               @suffix-click="showFiles({item:item ,value:data[item.fieldName],target:data,ref:tb.tableName})"
                               @blur="ValueChange(data,Fields[tb.tableName],item.fieldName)">
                      <template #suffix>
                        <i class="el-icon-plus"></i>
                      </template>
                    </vxe-input>
                  </div>
                  <vxe-input v-if="item.dataTypeID===7" v-model="data[item.fieldName]" placeholder="请输入..."
                             :readonly="item.editable===0||formData.statusCode!==0" clearable
                             @blur="ValueChange(data,Fields[tb.tableName],item.fieldName)"></vxe-input>
                </template>
              </vxe-form-item>
              <el-button class="addbut-red" icon="el-icon-delete" @click="removeEvent(items,tb.tableName)" plain>删除
              </el-button>
            </div>
          </vxe-form>
          <el-button class="addbut" type="primary" icon="el-icon-plus" @click="addDataSou(tb.tableName)">新增</el-button>
        </el-tab-pane></el-tabs>
    </div>
    <el-drawer
    v-model="processdrawer"
    title="审批流程"
    direction="btt"
    size="80%"
  >
    <sxPse :data="ApprovalData.task" :ish5="true"></sxPse>
    <vxe-form v-if="ApprovalData.do"
              style="position: absolute;width: 100%; bottom: 0px; padding: 10px; background-color: #fff;"
              title-colon
              ref="xForm"
              title-width="100"
              :data="ApprovalData"
              :rules="ApprovalRules"
              @submit="flowtodo">

            <vxe-form-item field="status" span="24" :item-render="{}">
                <template #default="{ data }">
                  <vxe-radio-group v-model="data.status" @click="approstatus">
                    <vxe-radio :label="8" content="同意"></vxe-radio>
                    <vxe-radio :label="7" content="退回"></vxe-radio>
                    <vxe-radio :label="9" content="拒绝"></vxe-radio>
                  </vxe-radio-group>
                </template>
              </vxe-form-item>
            <vxe-form-item field="opinion" span="24" :item-render="{}">
            <template #default="{ data }">
              <vxe-textarea v-model="data.opinion" placeholder="请输入审批意见" :autosize="{minRows: 3, maxRows: 3}" clearable></vxe-textarea>
            </template>
          </vxe-form-item>
            <vxe-form-item align="center" span="24">
              <template #default>
                <vxe-button type="submit" status="primary" content="提交"></vxe-button>
                <vxe-button type="reset" content="重置"></vxe-button>
              </template>
            </vxe-form-item>
          </vxe-form>
  </el-drawer>
    <DataGridSelect ref="DGE" :isequipment="isequipment" v-on:submit="getSourceData"></DataGridSelect>
    <FilesSelect ref="Files" :isequipment="isequipment" v-on:submit="getFilesData"></FilesSelect>
  </div>
</template>

<script>
import {getCurrentInstance, reactive, ref, toRefs, watch} from "vue"
import XEUtils from 'xe-utils'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
    formCheck,
    getDefault,
    getfilter,
    getSelectRule,
    loadExpand,
    rePost,
    RunExpand,
    updateRule
} from "/@/api/linkoo/form/index"
import {useRoute, useRouter} from 'vue-router'
import {Plus} from '@element-plus/icons-vue'
import {editForm} from "/@/api/linkoo/form"
import DataGridSelect from './select.vue'
import FilesSelect from './FilesSelect.vue'
import {mathAll} from "/@/utils/mathji"
import {getCode, getDingTalksCheck} from "../../../api/login";
import {getdingfileid, uploaddingfileid} from "../../../api/linkoo/form";
import sxPse from "./sxpse.vue"
import {flowTodo,getWorkFlowData} from "/@/api/linkoo/workflow";
export default {
  props: ['Fields', 'MT', 'DT', 'Combo', 'isequipment', 'Rules', 'ActRules', 'isNew', 'Title', 'DataSource', 'load', 'Linker','Template'],
  components: {DataGridSelect, FilesSelect,sxPse},
  setup(props, ctx) {
    const  { proxy }  = getCurrentInstance()
    let DGE = ref(null)
    let Files = ref(null)
    let refForm = ref(null)
    let router = useRouter()
    const route = useRoute()
    let state = reactive({
      RecordID:0,
      processdrawer:false,
      formData: {},
      validateCheck: true,
      OldMData: {},
      OldDData: {},
      selectMainData: {},
      DetailsData: {},
      selectTab: null,
      tableHeight: {},
      ApprovalData: {task:[]},
      resize: 0,
      template: {},
      linker: {},
      ManualActRules: {},
      rid: route.params.id,
      itemRefs: {},
      toolbarButtons: [
        {code: 'add', name: '新增'}, {code: 'copy', name: '复制'}, {code: 'clear', name: '清空'}, {code: 'delete', name: '删除'}
      ],
      load:true,
      selectDataGridTarget: {},
      selectFiels: {},
      ShowFooter: {},
      FooterFields: {},
      expandcfg: {},
      DataSource: {},
      expandField: [],
      expandData: [],
      filters:{},
      expandConfig: {
        lazy: true,
        loadMethod({row}) {
          return new Promise(resolve => {
            loadExpand(state.expandcfg).then(res => {
              state.expandField = res.data.field
              state.expandData = res.data.list
              resolve()
            })
          })
        },
        visibleMethod() {
          return false
        }
      }
      // firstload:false
    })
    watch(props, (ovl, evl) => {
      if (props.load&&state.load) {
        Load()
        GetWF()
      }
    })
    const Load = () => {
      // return
      XEUtils.arrayEach(props.DT, row => {
        state.ShowFooter[row.tableName] = false
        if (row['onSheet'] !== ''&&row['onSheet'].length!==0) {
          state.FooterFields[row.tableName] = row['onSheet']
          state.ShowFooter[row.tableName] = true
        }
      })
      // if (props.DataSource[props.MT.tableName]) {
      state.OldMData = XEUtils.omit(props.DataSource, 'ChildTables')
      state.formData = XEUtils.omit(props.DataSource, 'ChildTables')
      state.RecordID=state.formData.RecordID
      // }

      props.DT.forEach(row => {
        state.tableHeight[row.tableName] = 120
        state.DetailsData[row.tableName]=[]
      })
      if (props.DataSource.ChildTables) {
        state.OldDData = XEUtils.clone(props.DataSource.ChildTables, true)
        state.DetailsData = XEUtils.clone(props.DataSource.ChildTables, true)
      }
      XEUtils.objectEach(props.ActRules, async (items, key) => {
        let rules = XEUtils.filter(items, item => item.runTime.split(',').includes('999'))
        if (rules.length > 0) {

          state.ManualActRules[key] = rules
        }
      })

      if (props.isNew) {
        state.RecordID=0
        state.formData.statusCode=0
        getDefaults(state.formData, props.MT.tableID)
      }
      state.load=false
    }
    const getDefaults = (target, id) => {
      target['StatusCode'] = 0
      getDefault(id).then(res => {
        XEUtils.objectEach(res.data, (item, key) => {
          target[key] = item
        })
      })
      XEUtils.objectEach(props.ActRules, async (items) => {
        let selectrules = XEUtils.filter(items, item => item.runTime.split(',').includes('101') || item.runTime.split(',').includes('102'))
        for (let i = 0; i < selectrules.length; i++) {
          await loadSelectRules(selectrules[i])
        }
      })
    }
    const runActRules = (rule) => {
      switch (rule.ruleType) {
        case 1:
          loadSelectRules(rule)
          break
        case 2:
          runUpdateRule(rule)
          break
        case 3:
          runPostRule(rule)
          break
      }
    }
    const runPostRule = async (rule) => {
      if (rule.isExtFlow === 1 && rule.sourceType === 1) {
        if([1,2,9].includes(state.formData.statusCode)){
          ElMessage.error('单据状态已变更,不允许再次提交!')
          return
        }
        let files = [], corpId = '', kk = getDingTalksCheck()
        await getdingfileid(rule.ruleID, state.formData.RecordID).then(async res => {
          files = res.data['fileId'] || [];
          corpId = res.data.corpId;
        })
        if (files.length > 0) {
          if (!kk) {
            ElMessage.error('有附件需要在钉钉客户端环境中上传,请在钉钉客户端中重试!')
            return
          } else {
            ElMessage.info('开始传送钉钉表单')
            let sendFiles = files.length
            for (let i = 0; i < files.length; i++) {
              await getCode({type:'dingtalk',corpId:corpId}, async (code) => {
                //  this.dingCode=code
                if (!code) {
                  ElMessage.error('未取得钉钉用户code')
                  // this.sendingLoading = false
                  return
                }
                await uploaddingfileid(files[i], code).then(res => {
                  ElMessage.success(res.message)
                  sendFiles--
                  if (sendFiles === 0) {
                    ElMessage.success("附件上传完毕!")
                    dopotrule(rule)
                  }
                })
              })
            }
          }
        } else {
          dopotrule(rule)
        }

      } else {
        dopotrule(rule)
      }

    }
    const processbutton = ()=>{
      state.processdrawer=true
    }
    const GetWF=()=>{
      console.log(props.Template,state.formData.RecordID);
      getWorkFlowData(props.Template.templateCode,state.formData.RecordID).then(res=>{
        if (res.data.task!==undefined&&res.data.task!==''){
          console.log(res.data);
          state.ApprovalData=res.data
          if(res.data.do&&res.data.type===2){
            flowTodo(route.params.templateCode,route.params.id, state.ApprovalData.tid, {status:8,level:res.data.level}).then(res=>{
              GetWF()
            })
          }
        }

      })
    }
    const dopotrule = (rule) => {
      rePost(state.formData.RecordID, rule.ruleID).then(res => {
        if (res.code === 0) {
          if (rule.isExtFlow === 1 && rule.sourceType === 1) {
            state.formData.statusCode=1
          }
          ElMessage.success('成功执行[' + rule.ruleName + ']')
        }
      })
    }
    const runUpdateRule = (rule) => {
      let filterExpr = rule.sqlSchema
      const regex = /({(\S+)[.](\S+)})/gis
      let m
      let keys = [], table = [], vals = []
      while ((m = regex.exec(filterExpr)) !== null) {
        // 这对于避免零宽度匹配的无限循环是必要的
        if (m.index === regex.lastIndex) {
          regex.lastIndex++
        }
        m.forEach((match, groupIndex) => {
          if (groupIndex === 1) {
            keys.push(match)
          }
          if (groupIndex === 2) {
            table.push(match)
          }
          if (groupIndex === 3) {
            vals.push(match)
          }
        })
      }
      XEUtils.arrayEach(keys, (it, key) => {
        if (table[key] !== props.MT.tableName && XEUtils.filter(props.DT, item => item.tableName === table[key])) {
          const data = XEUtils.pluck(XEUtils.clone(state.itemRefs[key].getTableData().fullData, true), vals[key])
          filterExpr = filterExpr.replace(it, `'${data.join("','")}'`)
        } else {
          let val = XEUtils.get(state.formData, vals[key], "''")
          filterExpr = filterExpr.replace(it, val)
          filterExpr = filterExpr.replace('@RecordID', route.params.id.toString())
        }
      })
      updateRule(rule.ruleID, filterExpr, state.formData.RecordID).then(res => {
        if (res.code === 0) {
          ElMessage.success('成功执行[' + rule.ruleName + ']')
        }
      })
    }
    const loadSelectRules = async (rule) => {
      if (rule.ruleName === '合计' && XEUtils.toStringJSON(rule.sourceField).length === 0) {
        const r = XEUtils.toStringJSON(rule.targetField)
        r.forEach(row => {
          const t = row.tofield.split('.')
          const f = row.field.split('.')
          if (t[0] === props.MT.tableName) {
            if (props.isequipment) {
              const $tb = state.itemRefs[f[0]]
              state.formData[t[1]] = XEUtils.sum($tb.getTableData().fullData, f[1])
            } else {
              state.formData[t[1]] = XEUtils.sum(state.DetailsData[f[0]], f[1])
            }
          } else {
          }
        })
        return
      }
      let filterExpr = rule.filterExpr
      const regex = /({(\S+)[.](\S+)})/gis
      let m
      let keys = [], table = [], vals = []
      while ((m = regex.exec(filterExpr)) !== null) {
        // 这对于避免零宽度匹配的无限循环是必要的
        if (m.index === regex.lastIndex) {
          regex.lastIndex++
        }
        m.forEach((match, groupIndex) => {
          if (groupIndex === 1) {
            keys.push(match)
          }
          if (groupIndex === 2) {
            table.push(match)
          }
          if (groupIndex === 3) {
            vals.push(match)
          }
        })
      }
      XEUtils.arrayEach(keys, (it, key) => {
        if (table[key] !== props.MT.tableName && filterExpr.indexOf(' in ') > 1) {
          const data = XEUtils.pluck(XEUtils.clone(state.itemRefs[key].getTableData().fullData, true), vals[key])
          filterExpr = filterExpr.replace(it, `'${data.join("','")}'`)
        } else {
          let val = XEUtils.get(state.formData, vals[key], '')
          if (val.length === 0) {
            const data = state.itemRefs[table[key]].getCurrentRecord()
            val = XEUtils.get(data, vals[key], "")
          }

          filterExpr = filterExpr.replace(it, val)
        }
      })
      await GetSelectRules(rule, filterExpr)
    }
    const GetSelectRules = async (rule, filterExpr) => {
      await getSelectRule(rule.ruleID, filterExpr).then(res => {
        if (res.data.list) {
          fromSelectRule(rule, res.data.list)
          ElMessage.success('成功执行[' + rule.ruleName + '],数据已添加')
        } else {
          ElMessage({type: 'info', message: '成功执行[' + rule.ruleName + '],但未到取到数据',})
        }
      })
    }
    const fromSelectRule = (rule, data) => {
      if (data === null) return
      const topull = JSON.parse(rule['targetField'])
      let TB = {}, link = false, linkstr = ''
      topull.forEach(row => {
        const tf = row['tofield'].split('.')
        if (TB[tf[0]] === undefined) TB[tf[0]] = {}
        TB[tf[0]][tf[1]] = row['field'].indexOf('.') > -1 ? row['field'].split('.')[1] : row['field']
        if (row.type === 'keys') {
          link = true
          linkstr = tf[1]
        }
      })

      XEUtils.objectEach(TB, (fields, key) => {
        if (key === props.MT.tableName) {
          XEUtils.objectEach(fields, (f, t) => {
            state.formData[t] = data[0][f]
          })
        } else {
          if (props.isequipment) {
            const $tb = state.itemRefs[key]
            let records = []
            data.forEach(row => {
              let record = {}
              XEUtils.objectEach(fields, (f, t) => {
                record[t] = row[f]
              })
              records.push(record)
            })
            if (rule.clearAllRow === 1) {
              $tb.remove()
            }
            if (link) {
              const dd = XEUtils.clone($tb.getTableData().fullData, true)
              dd.map(row => {
                const record = XEUtils.find(records, r => r[linkstr] === row[linkstr])
                if (record) {
                  XEUtils.objectEach(record, (item, key) => {
                    row[key] = item
                  })
                }
                return row
              })
              $tb.reloadData(dd)
            } else {
              $tb.insertAt(records, -1)
            }
            state.resize = key

          } else {
            const Max = XEUtils.max(state.DetailsData[key], 'Seq')
            let seq = 0
            if (Max !== undefined) {
              seq = Max[['Seq']]
            }
            const defrecord = {}
            props.Fields[key].forEach(row => {
              defrecord[row.fieldName] = null
            })
            if (rule.clearAllRow === 1) {
              state.DetailsData[key] = []
            }
            data.forEach(row => {
              let record = {}
              XEUtils.objectEach(fields, (f, t) => {
                record[t] = row[f]
              })
              record['Seq'] = seq + 1
              state.DetailsData[key].push(record)
              seq++
            })
          }
        }
      })
    }
    const getextend = (data, field) => {
      let extend = XEUtils.toStringJSON(data['Extend'] ? data['Extend'] : '{}')
      if (extend[field.fieldName] === undefined) {
        extend[field.fieldName] = data[field.fieldName]
        data['Extend'] = XEUtils.toJSONString(extend)
      }
      return extend[field.fieldName]
    }
    const ValueChange = async (data, fields, fieldName) => {

      let source = XEUtils.clone(data, true)
      let extend = XEUtils.toStringJSON(data['Extend'])
      source = XEUtils.objectMap(source, item => item === null ? 0 : item)
      fields.forEach(field => {
        if (field.componentType === 9 && field.componentFieldName !== '') {

          const jgm = mathAll(field.componentFieldName, source)
          data[field.fieldName] = jgm ? XEUtils.toFixed(jgm, field.fieldPrecision) : jgm
        }
        if (field.dataTypeID !== 6 && field.componentType === 0 && extend[field.fieldName] !== null && extend[field.fieldName] !== undefined) {
          extend[field.fieldName] = data[field.fieldName]
        }
      })
      console.log("dow.........",props.ActRules)
      data['Extend'] = JSON.stringify(extend)
      XEUtils.objectEach(props.ActRules, async (items) => {
        let selectrules = XEUtils.filter(items, item => item.runTime.split(',').includes('106') && XEUtils.includes(item['onChangeFileld'].split(','), fieldName))
        for (let i = 0; i < selectrules.length; i++) {

          await loadSelectRules(selectrules[i])
        }
      })

    }
    const formatData = ({cellValue, row, column}) => {
      let extend = XEUtils.toStringJSON(row['Extend'])
      if (extend[column.field] === null || extend[column.field] === undefined) {
        extend[column.field] = cellValue ? cellValue : ''
      }
      return XEUtils.get(extend, column.field)
    }

    const buttonsClick = async ({code, button, $event}, name, index) => {
      state.selectTab = name
      switch (code) {
        case 'add': {
          const {row: fnewRow} = await state.itemRefs[name].insertAt({RecordID: 0, Seq: null, Extend: '{}'}, -1)
          await getAutoCode(props.Fields[state.selectTab], fnewRow, null)
          await state.itemRefs[name].setActiveCell(fnewRow, props.Fields[state.selectTab][0]['fieldName'])
          await state.itemRefs[name].setCurrentRow(fnewRow)
          // this.tableHeight[this.selectTab]=this.tableHeight[this.selectTab]>500?this.tableHeight[this.selectTab]:this.tableHeight[this.selectTab]+40
          state.resize = fnewRow['_X_ID']

          break
        }
        case 'delete': {
          const Fieldrows = state.itemRefs[name].getCheckboxRecords()
          if (Fieldrows.length > 0) {
            ElMessageBox.confirm("您确定要删除该数据?", "警告", {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(() => {
              state.resize = Fieldrows[0]['_X_ID']
              state.itemRefs[name].remove(Fieldrows)
            })
          } else {
            ElMessage({type: 'info', message: '选择数据后再删除!',})
          }
          break
        }
        case 'clear': {
          ElMessageBox.confirm("您确定要清空数据吗?", "警告", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            state.itemRefs[name].remove()
          })
          break
        }
        case 'copy': {
          const Fieldrows = state.itemRefs[name].getCheckboxRecords()
          if (Fieldrows.length > 0) {
            const fields = Fieldrows.map((row, index) => {
              row['RecordID'] = 0;
              row['Seq'] = null;
              row['Extend'] = '{}';

              delete row['_X_ROW_KEY'];
              return row
            })
            await state.itemRefs[name].insertAt(fields, -1)
            // this.tableHeight[this.selectTab]=40*Fieldrows.length+120>500?500:this.tableHeight[this.selectTab]+40*Fieldrows.length
          } else {
            ElMessage({
              type: 'info',
              message: '选择数据后再复制!',
            })
          }
          break
        }
      }
    }
    const getAutoCode = (fields, target, field) => {
      if (field) {
        field = XEUtils.find(fields, item => item.fieldName === field)
        if (field.componentType === 5 && target[field.fieldName] !== '') {
          ElMessageBox.confirm("是否确认重新获取编号?", "警告", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            ElMessage({
              type: 'info',
              message: '确认重新获取编号',
            })
            // getAutoCodes(this.$route.name,field.componentID).then(res=>{
            //     target[field.fieldName]=res.data
            // })
          }).catch(function () {
          });
        }
      } else {
        XEUtils.objectEach(fields, (item, key) => {
          if (item.default !== '') {
            target[item.fieldName] = item.default
          }
          if (item.componentType === 5 && XEUtils.toValueString(target[item.fieldName]) === '') {
            // getAutoCodes(this.$route.name,item.componentID).then(res=>{
            //     target[item.fieldName]=res.data
            // })
          }
        })
      }
    }
    const showSource = async ({item, value, target, ref}) => {
      if (item.componentFilterExpr !== '' && item.componentType === 3) {
        if (state.filters[item.fieldName]===undefined){
          state.filters[item.fieldName]=XEUtils.clone(item.componentFilterExpr, true)
        }
        item.componentFilterExpr = XEUtils.clone( state.filters[item.fieldName], true)
          const regex = /({(\S+)})/gis
          let m
          let keys = [], vals = []
          while ((m = regex.exec(item.componentFilterExpr)) !== null) {
            // 这对于避免零宽度匹配的无限循环是必要的
            if (m.index === regex.lastIndex) {
              regex.lastIndex++
            }
            // 结果可以通过`m变量`访问。
            m.forEach((match, groupIndex) => {
              if (groupIndex === 1) {
                keys.push(match)
              }
              if (groupIndex === 2) {
                vals.push(match)
              }
            })
          }

          XEUtils.arrayEach(keys, (it, key) => {
            // 主字段查找
            let val = XEUtils.get(state.formData, vals[key], '')
            if (val === '') {
              // 明细表行数据查找
              val = XEUtils.get(target, vals[key], '')
            }
            if (item.componentFilterExpr.indexOf(' in ') > 1) {
              const data = XEUtils.pluck(XEUtils.clone( state.DetailsData[ref], true), vals[key])

              let vv=data?data.join("','"):''
              item.componentFilterExpr  = item.componentFilterExpr .replace(it, `'${vv}'`)
            }else{
              item.componentFilterExpr  = item.componentFilterExpr .replace(it, val)
            }

          })

      }
      DGE.value.Data = Object.assign({}, {field: item, value: value, data: state.formData})
      DGE.value.todo()
      // this.$refs.DGE.showDialog = true
      state.selectDataGridTarget = {field: item, target: target, ref: ref}
    }
    const showFiles = async ({item, value, target, ref, multiple, fileType}) => {
      Files.value.Data = Object.assign({}, {field: item, value: value})
      Files.value.dataTypeID = item.dataTypeID
      Files.value.todo()
      Files.value.multiple = multiple
      Files.value.fileType = fileType
      Files.value.title = fileType === 'images' ? '图片选择' : '附件选择'

      Files.value.fileSize = item.fieldPrecision === 0 ? 8 : item.fieldPrecision

      state.selectFiels = {field: item, target: target, ref: ref}
    }
    const getDTdefault = async (table) => {
      const tb = XEUtils.find(props.DT, item => item.tableName === table)
      const row = {RecordID: state.RecordID, Seq: null, Extend: '{}'}
      props.Fields[table].forEach(f => {
        switch (f.dataTypeID) {
          case 1:
          case 4:
            row[f['fieldName']] = null
            break
          case 2:
          case 3:
            row[f['fieldName']] = 0
            break
        }
      })
      await getDefault(tb.tableID).then(res => {
        XEUtils.objectEach(res.data, (item, key) => {
          row[key] = item
        })
      })
      return row
    }
    const getSourceData = ({data, data2, C}) => {
      const field = JSON.parse(state.selectDataGridTarget.field.componentFieldName)
      const target = state.selectDataGridTarget.target
      const keys = state.selectDataGridTarget.ref
      // let isBT = true
      // if (XEUtils.has(keys=== props.MT.tableName)) {
      //   isBT = false
      // }
      console.log(data,target,'lllllllll')
      if (keys=== props.MT.tableName) {
        XEUtils.objectEach(field, (item, key) => {
          target[key] = XEUtils.pluck(data, item.v).join(",")
          let extend = XEUtils.toStringJSON(target['Extend'])
          const F = props.Fields[keys].find(item => item.fieldName === key)
          if (F['componentType'] === 3) {
            extend[key] = XEUtils.pluck(data, item.v).join(",")
          }
          target['Extend'] = XEUtils.toJSONString(extend)
        })
      } else {
        const tb = XEUtils.find(props.DT, item => item.tableName === keys)
        data.forEach(async (row, index) => {
          const newrow = await getDTdefault(keys)
          if (tb.layoutStyle.length > 0) {
            newrow[tb.layoutStyle[1]] = state.parentV
          }
          XEUtils.objectEach(field, (item, key) => {
            // 对象迭代器，只能用于遍历对象，性能高于 each
            if (row[item.v]) {
              newrow[key] = row[item.v]
            }

            let extend = XEUtils.toStringJSON(newrow['Extend'])
            const F = props.Fields[keys].find(item => item.fieldName === key)
            if (F!==undefined &&F['componentType'] === 3) {
              extend[key] = data[index][item.v]
            }
            newrow['Extend'] = XEUtils.toJSONString(extend)
          })

          XEUtils.objectEach(props.Fields[keys], (item, key) => {
            if (item.componentType === 9 && item.componentFieldName !== '') {
              const jgm = mathAll(item.componentFieldName, newrow)
              newrow[item.fieldName] = jgm ? XEUtils.toFixed(jgm, item.fieldPrecision) : jgm
            }
          })
          if (tb.layoutStyle.length>0&&newrow[tb.layoutStyle[0]] === newrow[tb.layoutStyle[1]]) {
            return false
          }
          if (index === 0) {
            XEUtils.objectEach(newrow, (item, key) => {
              if (item) {
                target[key] = item
              }
            })
          } else {
            state.DetailsData[keys].push(newrow)
          }
        })
      }
      ValueChange(target, props.Fields[state.selectDataGridTarget.ref], state.selectDataGridTarget.field.fieldName)
    }
    const newFieldRow = (tablename) => {
      const row = {RecordID: 0, Seq: null, Extend: '{}'}
      props.Fields[tablename].forEach(f => {
        row[f['fieldName']] = null
      })
      return row
    }
    // 移动端
    const addDataSou = (tableName) => {
      state.selectTab = tableName
      if(state.DetailsData[state.selectTab]===undefined){
        state.DetailsData[state.selectTab]=[]
      }
      const Max = XEUtils.max(state.DetailsData[state.selectTab], 'Seq')
      let seq = 0
      if (Max !== undefined) {
        seq = Max[['Seq']]
      }
      state.DetailsData[state.selectTab].push(getNewitem(state.selectTab, seq))
    }
    const getNewitem = (table, maxseq) => {
      const def = {}
      props.Fields[table].forEach(row => {
        def[row.fieldName] = null
      })
      def['Seq'] = maxseq + 1
      return def
    }
    // 删除
    const removeEvent =(items,row)=>{
      state.DetailsData[row].forEach((item,index)=>{
        if(item===items){
          state.DetailsData[row].splice(index,1)
        }
      })
    }
    const getFilesData = ({data, filesName, extdata}) => {
      state.selectFiels.target[state.selectFiels.field.fieldName] = data
      let extend = XEUtils.toStringJSON(state.selectFiels.target['Extend'])
      extend[state.selectFiels.field.fieldName] = filesName
      if (extdata.length > 0) {
        const field = JSON.parse(state.selectFiels.field.componentFieldName)
        for (let i = 0; i < extdata.length; i++) {
          if (i === 0) {
            XEUtils.objectEach(field, (item, key) => {
              state.selectFiels.target[key] = extdata[0][item]
            })
          } else {
            let rows = {}, ext = {}
            rows[state.selectFiels.field.fieldName] = data
            ext[state.selectFiels.field.fieldName] = filesName
            rows['Extend'] = XEUtils.toJSONString(ext)
            XEUtils.objectEach(field, (item, key) => {
              rows[key] = extdata[i][item]
            })
            // this.$refs[state.selectFiels.ref][0].insertAt(rows,-1)
          }
        }
      }

      state.selectFiels.target['Extend'] = XEUtils.toJSONString(extend)
    }

    const Save = async () => {

      // if (state.formData.StatusCode !== 0) {
      //   ElMessage({
      //     message: '单据审核状态非初始状态.不能执行保存!',
      //     type: 'error',
      //   })
      //   return
      // }
      state.validateCheck = true
      const Data = {}
      Data['D'] = await getDetailData()
      Data['M'] = await getMainData()
      if (!state.validateCheck) {
        return;
      }
      await editForm(route.params.templateCode, route.params.id, Data).then( (response) => {
        if (response.code === 0) {
          ElMessage.success('单据操作成功')
          if (props.isNew) {
            const url= '/form/edit/' + route.params.templateCode + "/" +response.data.id
            // proxy.mittBus.on('onTagsViewRefreshRouterView',url)
            // state.formData.RecordID=response.data.id
            // route.params.id=response.data.id
            // for (const tb of props.DT) {
            //   state.itemRefs[tb.tableName].getTableData().fullData.map((row, index) => {
            //     if (row['Seq'] !== undefined || row['Seq'] !== null) {
            //       row['RecordID']=response.data.id
            //     }
            //     return row
            //   })
            //
            // }
           router.replace(url)
          //  router.push({ params: { id: response.data.id } , replace: true })
          }
        } else {
          ElMessage.error('单据操作出错')
        }
      })

    }
    const getDetailData = async () => {
      const Data = {}
      for (const tb  of props.DT) {
        const indext = props.DT.indexOf(tb);
        let data = []
        Data[tb.tableName] = {DE: [], DD: [], DA: []}
        const errMap = await state.itemRefs[tb.tableName+'_'+indext].validate()
        if (errMap) {
          state.validateCheck = false
          continue;
        }
        const olddata = state.OldDData[tb.tableName] || []
        if (props.isequipment) {
          let max = XEUtils.max(olddata, 'Seq')
              if (max===undefined){
                max=1
              }else{
                max=max['Seq']
              }

          data = state.itemRefs[tb.tableName].getTableData().fullData.map((row, index) => {
            if (row['Seq'] === undefined || row['Seq'] === null) {
              row['Seq'] = max + 1
              max++
            }
            delete row['_X_ROW_KEY']
            return row
          })

          state.itemRefs[tb.tableName].reloadData(data)
        } else {
          data = state.DetailsData[tb.tableName].concat([])
        }
        data.forEach(rowData => {
          let od = XEUtils.find(olddata, item => item.Seq === rowData.Seq)
          if (od === undefined) {
            Data[tb.tableName].DA.push(rowData)
          } else {
            const updateData = {}
            XEUtils.objectEach(od, (item, key) => {
              if (item !== rowData[key] && key !== 'Seq' && key !== 'RecordID') {
                updateData[key] = rowData[key]
              }
            })
            if (!XEUtils.isEmpty(updateData)) {
              Data[tb.tableName].DE.push(XEUtils.assign(updateData, {
                'RecordID': rowData['RecordID'],
                'Seq': rowData['Seq']
              }))
            }
          }
        })
        olddata.forEach(row => {
          if (XEUtils.find(data, item => item.Seq === row.Seq) === undefined) {
            Data[tb.tableName].DD.push(row)
          }
        })
      }
      return Data
    }
    const getMainData = async () => {
      const n = {}
      let data = {}
      const errMap = await refForm.value.validate()
      if (errMap) {
        state.validateCheck = false
        return
      }
      if (state.formData.RecordID === 0 || props.isNew) {
        data = state.formData
        data.RecordID = 0
        data.StatusCode = 0
      } else {
        XEUtils.objectEach(XEUtils.omit(state.formData, 'ChildTables'), (item, key) => {
          if ((key === 'Extend') || (state.OldMData[key] !== null && item !== state.OldMData[key]) || (state.OldMData[key] === null && item)) {
            data[key] = item
          }
        })
      }
      n[props.MT.tableName] = data
      const Data = XEUtils.clone(n, true)
      return Data
    }
    const sumNum = (list, field) => {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count
    }
    const showExpand = (table, row, lid) => {
      state.expandcfg = {id: lid, row: row}
      const $tb = state.itemRefs[table]
      $tb.toggleRowExpand(row)
    }
    const doExpand = (row, id) => {
      RunExpand({row: row, id: id}).then(res => {
        if (res.code === 0) {
          ElMessage.success('操作成功')
        } else {
          ElMessage.error('操作出错' + res.msg)
        }
      })

    }
    const footerMethod = ({$table, columns, data}) => {
      const tablename = $table.props.id
      if (state.ShowFooter[tablename]) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return '合计'
            }
            if (state.FooterFields[tablename].includes(column.property)) {
              return sumNum(data, column.property)
            }
            return null
          })
        ]
      }
    }
      const handleCheck = (status) => {

          ElMessageBox.confirm(
              '是否确认' + (status > 0 ? "审核" : "反审") + "操作?",
              '警告',
              {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
              }
          ).then(() => {
              formCheck({
                  template: props.Template.templateCode,
                  table: props.MT.tableName,
                  ids: state.formData.RecordID,
                  status: status
              }).then(res => {
                  const url= '/form/edit/' + props.Template.templateCode + "/" +state.formData.RecordID
                  ElMessage({
                      message: '操作成功',
                      grouping: true,
                      type: 'success',
                  })
                  location.reload();
              })
          })
      }
    return {
      ...toRefs(state)
      , Load,
      getDefaults,
      loadSelectRules,
      XEUtils,
      DGE,handleCheck,
      Files,
      Plus,
      refForm,
      getextend,
      showExpand,
      ValueChange,
      GetWF,
      formatData,
      getMainData,
      getAutoCode,
      buttonsClick,
      showSource,
      showFiles,
      getSourceData,
      newFieldRow,
      addDataSou,
      getNewitem,
      doExpand,
      runPostRule,
      runActRules,
      getFilesData,
      Save,
      GetSelectRules,
      getDetailData,
      footerMethod,
      removeEvent,
      processbutton
    }
  }
}
</script>

<style scoped>
.expand-wrapper {
  padding: 10px;
}

.index {
  position: absolute
}

.my-search.vxe-input .vxe-input--suffix {
  width: 33px;
  text-align: center;
  border: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  cursor: pointer;
  right: 0px;
}

.my-search.vxe-input .vxe-input--inner {
  border: 1px solid #dcdfe6;
}
.sxform .vxe-form--item .vxe-form--item-inner .vxe-form--item-content {
  width: 100%;
}
.stable {
  padding: 10px;
  box-sizing: border-box;
}

.ke {
  background-color: #ffffff;
  border: 1px dashed #3b3b3b;
  margin: 10px 0;
  padding: 10px;
  border-radius: 5px;
}

.ke .lie {
  display: flex;
  margin: 5px 0;
  align-items: center;
}

.ke .lie span {
  width: 90px;
}

.ke .lie input {
  flex: 1;
  height: 30px;
  border: 1px solid rgb(152, 152, 152);
  border-radius: 3px;
}

.addbut {
  width: 100%;
}

.addbut-red:focus, .addbut-red:active {
  border: 1px solid #ff8989;
  background-color: #ff898918;
  color: #ff8989;
}

.addbut-red {
  width: 100%;
  border: 1px solid #ff8989;
  background-color: #ff898918;
  color: #ff8989;
  margin-top: 10px;
}

.m-10 {
  margin-bottom: 10px;
}
</style>